package com.shiyi.filters;

import org.springframework.lang.Nullable;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义编码过滤器
 * 一般来说，post请求可以通过设置request和response的编码来控制
 * 而get请求需要在tomcat的server.xml中设置encoding="UTF-8"
 * @author wangzhanshuai
 * @date 2021/1/21 6:48 下午
 * @since 1.0
 */
public class MyCharacterFilter extends OncePerRequestFilter {

    private String encoding;

    public MyCharacterFilter() {
    }

    public MyCharacterFilter(String encoding) {
        this.encoding = encoding;
    }

    @Nullable
    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(@Nullable String encoding) {
        this.encoding = encoding;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("MyCharacterFilter start...");
        String encoding = getEncoding();
        System.out.println(encoding);
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        filterChain.doFilter(request, response);
        System.out.println("MyCharacterFilter end...");
    }
}
